<template>
  <div class="chat-layout" :class="{ 'with-medical': store.showMedicalPanel }">
    <!-- 左侧：模型选择（上半部分）和会话历史（下半部分） -->
    <div class="left-column">
      <!-- 上半部分：模型选择 -->
      <div class="left-section model-selector">
        <ModelSelector />
      </div>
      
      <!-- 下半部分：会话历史 -->
      <div class="left-section chat-history">
        <ChatHistory />
      </div>
    </div>

    <!-- 中间：聊天 -->
    <div class="middle-column">
      <!-- 普通聊天模式 -->
      <div v-if="!store.showMedicalPanel" class="normal-chat">
        <div class="chat" ref="chatRef">
          <div class="chat-content" ref="contentRef">
            <!-- 消息项 - 使用flex布局更便于控制顺序 -->
            <div
              v-for="(m, i) in store.messages"
              :key="i"
              :class="['msg', m.role === 'user' ? 'user' : 'assistant']"
            >
              <!-- AI消息：头像在左，气泡在右 -->
              <div v-if="m.role !== 'user'" class="avatar" aria-hidden="true">
                <span>AI</span>
              </div>
              
              <div class="bubble">
                <MarkdownRenderer :content="m.content" />
              </div>
              
              <!-- 用户消息：头像在右，气泡在左（放在气泡后面实现右对齐） -->
              <div v-if="m.role === 'user'" class="avatar" aria-hidden="true">
                <span>你</span>
              </div>
            </div>

            <div ref="endRef" class="scroll-anchor"></div>
          </div>
        </div>

        <div class="input-bar">
          <textarea
            v-model="input"
            :placeholder="placeholder"
            :disabled="store.streaming"
            @keydown.enter.exact.prevent="send"
          />
          <button class="btn primary" :disabled="!input.trim() || store.streaming" @click="send">发送</button>
          <button class="btn ghost" :disabled="!store.streaming" @click="abort">中断</button>
        </div>
      </div>

      <!-- 医疗对话模式（基于demo4.py） -->
      <div v-else class="medical-chat">
        <div class="medical-chat-header">
          <h3>🔍 Med-DistillFL影像分析工作台</h3>
        </div>
        
        <!-- 主内容区 -->
        <div class="medical-content">
          <!-- 输入侧边栏 -->
          <div class="input-sidebar">
            <div class="image-upload-section">
              <h4>📷 上传医学影像</h4>
              <div class="upload-area" :class="{ 'drag-over': dragOver }" 
                   @drop="handleDrop" 
                   @dragover.prevent="dragOver = true"
                   @dragleave="dragOver = false"
                   @click="triggerFileInput">
                <input ref="fileInput" type="file" accept="image/*" @change="handleFileSelect" style="display: none;">
                <div v-if="!selectedImage" class="upload-placeholder">
                  <div class="upload-icon">📁</div>
                  <p>点击或拖拽上传医学影像</p>
                  <p class="upload-hint">支持 JPG, PNG, DICOM 等格式</p>
                </div>
                <div v-else class="image-preview">
                  <img :src="imagePreviewUrl" alt="医学影像预览">
                  <button class="remove-image" @click.stop="removeImage">✕</button>
                </div>
              </div>
            </div>
            
            <!-- 高级参数设置 -->
            <div class="advanced-params">
              <h5>高级参数设置</h5>
              <div class="param-row">
                <label>生成温度: {{ temperature }}</label>
                <input type="range" v-model="temperature" min="0" max="1" step="0.1" class="slider">
              </div>
              <div class="param-row">
                <label>Top P 参数: {{ topP }}</label>
                <input type="range" v-model="topP" min="0" max="1" step="0.1" class="slider">
              </div>
            </div>
            
            <!-- 分析指令输入 -->
            <div class="analysis-input">
              <label>分析指令</label>
              <textarea v-model="inputText" rows="3" 
                        placeholder="请输入您的问题..."></textarea>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
              <button class="btn primary analyze-btn" 
                      @click="startAnalysis" 
                      :disabled="!selectedImage || analyzing">
                {{ analyzing ? '分析中...' : '开始分析' }}
              </button>
              <button class="btn secondary" @click="clearInput">清空输入</button>
            </div>
          </div>

          <!-- 聊天主界面 -->
          <div class="chat-main">
            <div class="chatbot-container" ref="medicalChatContainer">
              <div v-if="chatHistory.length === 0" class="no-messages">
                <p>请上传医学影像并开始分析</p>
              </div>
              <div v-else class="chat-messages">
                <div v-for="(message, index) in chatHistory" :key="index" class="message-item">
                  <div class="message-header">
                    <span class="message-role">{{ message.role }}</span>
                    <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                  </div>
                  <div class="message-content" v-html="renderMarkdown(message.content)"></div>
                </div>
              </div>
              <div v-if="analyzing" class="analyzing-indicator">
                <div class="spinner"></div>
                <span>AI正在分析医学影像，请稍候...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 报告生成区 -->
        <div class="report-section">
          <div class="report-actions">
            <button class="btn primary" @click="generateReport" :disabled="!chatHistory.length || generatingReport">
              {{ generatingReport ? '生成中...' : '生成诊疗报告' }}
            </button>
            <button class="btn secondary" @click="downloadReport" :disabled="!medicalReport">
              下载报告
            </button>
          </div>
          <div v-if="medicalReport" class="report-content">
            <div class="markdown-content" v-html="renderMarkdown(medicalReport)"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：医疗影像分析面板 -->
    <div v-if="store.showMedicalPanel" class="right-column">
      <MedicalPanel />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import {useChatStore} from '@/stores/chat';
import { API_BASE_URL, MODELS } from '@/config/api';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import ChatHistory from '@/components/ChatHistory.vue';
import MedicalPanel from '@/components/MedicalPanel.vue';

const store = useChatStore();
const chatRef = ref<HTMLElement | null>(null);
const contentRef = ref<HTMLElement | null>(null); // ✅ 新增：内容容器
const endRef  = ref<HTMLElement | null>(null);   // ✅ 锚点

const input = ref('');
const placeholder = '请输入内容，Enter 发送。';

let controller: AbortController | null = null;

// 医疗对话模式的数据
const selectedImage = ref<File | null>(null);
const imagePreviewUrl = ref<string>('');
const inputText = ref('');
const dragOver = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);

// 分析相关状态
const analyzing = ref(false);
const generatingReport = ref(false);

// 高级参数
const temperature = ref(0.8);
const topP = ref(0.4);

// 聊天历史和分析结果
const chatHistory = ref<Array<{role: string, content: string, timestamp: string}>>([]);
const medicalReport = ref<string>('');

// 医疗对话模式的滚动控制
const medicalChatContainer = ref<HTMLElement | null>(null);


onMounted(async () => {
  // 刷新后拉取会话列表（不自动选中）
  await store.fetchSessions();
});
async function ensureSessionIfNeeded(seedTitle?: string){
  if (store.currentSessionId) return;
  const id = await store.createSession();        // ✅ 不传参
  if (seedTitle) {
    await store.renameSession(id, seedTitle.slice(0, 40)); // ✅ 用首条消息做标题
  }
}

async function send(){
  const content = input.value.trim();
  if(!content || store.streaming) return;

  // 没有选中的会话则自动创建
  await ensureSessionIfNeeded(content);
  // 再次确认：如果仍没有会话，直接返回
  if(!store.currentSessionId) return;

  // 置顶当前会话（可选，但体验更好）
  store.touchSession(store.currentSessionId);

  store.appendMessage({ role:'user', content });
  store.appendMessage({ role:'assistant', content: '' });

  input.value = '';
  store.setStreaming(true);
  controller = new AbortController();

  const modelParam = MODELS[store.model].apiParam;

  try{
    const r = await fetch(`${API_BASE_URL}/api/chat/stream?session_id=${store.currentSessionId}&model=${modelParam}`, {
      method: 'POST',
      headers: { 'Content-Type':'application/json' },
      body: JSON.stringify({ messages: store.messages }),
      signal: controller.signal,
    });
    if(!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);
    // 会话有新消息，更新“最近使用时间”并把它顶到列表前面
    store.touchSession(store.currentSessionId);
    const reader = r.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while(true){
      const { value, done } = await reader.read();
      if(done) break;
      buffer += decoder.decode(value, { stream: true });

      const parts = buffer.split('\n\n');
      for(let i=0; i<parts.length-1; i++){
        const chunk = parts[i];
        if(chunk.startsWith('data: ')){
          const payload = chunk.slice(6).trim();
          if(payload !== '[DONE]') store.updateLastAssistantDelta(payload);
        }else{
          store.updateLastAssistantDelta(chunk);
        }
      }
      buffer = parts[parts.length-1];
    }
  }catch(err){
    store.updateLastAssistantDelta(`\n\n> 请求中断或失败：${String(err)}`);
  }finally{
    store.setStreaming(false);
    controller = null;
  }
}
function abort(){ if(controller) controller.abort(); }
onBeforeUnmount(() => { if(controller) controller.abort(); });


// 是否“贴底”状态（用户没主动往上滚）
const shouldStick = ref(true);
const SCROLL_TOL = 32; // 距离底部多少像素内视为“贴底”
function isAtBottom(el: HTMLElement){
  return el.scrollHeight - (el.scrollTop + el.clientHeight) <= SCROLL_TOL;
}
function onChatScroll(){
  if (!chatRef.value) return;
  shouldStick.value = isAtBottom(chatRef.value);
}
function autoScroll(force = false){
  const el = chatRef.value;
  if (!el) return;
  if (force || shouldStick.value) {
    // 想要动画可用 behavior: 'smooth'（流式时可能有轻微动画累积）
    el.scrollTo({ top: el.scrollHeight });
  }
}
// 用锚点滚到底；流式时用 behavior:'auto'，避免平滑动画落后
function scrollToEnd(force = false){
  const el = chatRef.value;
  const anchor = endRef.value;
  if (!el || !anchor) return;

  if (force || shouldStick.value) {
    // 双 rAF，等一轮/两轮布局（Markdown/公式/代码块）
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        anchor.scrollIntoView({ block: 'end', behavior: 'auto' });
      });
    });
  }
}
// 1) 新增消息（插入 user + 占位 assistant）时，强制到底
watch(() => store.messages.length, async () => {
  await nextTick();
  scrollToEnd(true);
});
// 监听“最后一条消息内容变化”（流式增量），仅在贴底时滚动
watch(
  () => store.messages.length ? store.messages[store.messages.length - 1].content : '',
  async () => {
    await nextTick();
    autoScroll(false);
  }
);
// 2) 流式增量：仅在贴底时跟随
watch(
  () => store.messages.length ? store.messages[store.messages.length - 1].content : '',
  async () => {
    await nextTick();
    scrollToEnd(false);
  }
);
onMounted(() => {
  chatRef.value?.addEventListener('scroll', onChatScroll, { passive: true });
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('scroll', onChatScroll);
});
// 4) ✅ 观察“内容容器”尺寸变化（Markdown 渲染/代码高亮/数学公式/行号等都会触发）
let roContent: ResizeObserver | null = null;
onMounted(() => {
  if (contentRef.value) {
    roContent = new ResizeObserver(() => scrollToEnd(false));
    roContent.observe(contentRef.value);
  }
});
onBeforeUnmount(() => {
  roContent?.disconnect();
  roContent = null;
});
// 5) ✅ 监听图片加载（子元素 load 冒泡不到父，但在捕获阶段能监听到）
function onImgLoad(){ scrollToEnd(false); }
onMounted(() => {
  chatRef.value?.addEventListener('load', onImgLoad, true); // useCapture = true
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('load', onImgLoad, true);
});

// 医疗对话模式的方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    setSelectedImage(file);
  }
};

const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('image/')) {
    setSelectedImage(file);
  }
};

const setSelectedImage = (file: File) => {
  selectedImage.value = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const removeImage = () => {
  selectedImage.value = null;
  imagePreviewUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

const startAnalysis = async () => {
  if (!selectedImage.value) return;
  
  analyzing.value = true;
  
  try {
    // 如果是第一次分析（没有输入文本），使用默认的诊断提示
    if (!inputText.value.trim() && chatHistory.value.length === 0) {
      inputText.value = 'AI初步诊断';
    }
    
    // 调用分析API
    const formData = new FormData();
    formData.append('image', selectedImage.value);
    formData.append('input_text', inputText.value);
    formData.append('temperature', temperature.value.toString());
    formData.append('top_p', topP.value.toString());
    
    const response = await fetch(`${API_BASE_URL}/api/medical/analyze-complete`, {
      method: 'POST',
      body: formData
    });
    
    if (response.ok) {
      const result = await response.json();
      
      // 添加用户输入到聊天历史
      if (inputText.value.trim()) {
        chatHistory.value.push({
          role: '用户',
          content: inputText.value,
          timestamp: new Date().toISOString()
        });
      }
      
      // 添加AI回复到聊天历史
      chatHistory.value.push({
        role: 'AI',
        content: result.analysis_result,
        timestamp: new Date().toISOString()
      });
      
      // 清空输入
      inputText.value = '';
      
      // 滚动到底部显示新消息
      scrollToMedicalChatBottom();
      
    } else {
      const errorMsg = '分析失败，请检查网络连接或稍后重试';
      chatHistory.value.push({
        role: '系统',
        content: errorMsg,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    console.error('分析请求失败:', error);
    chatHistory.value.push({
      role: '系统',
      content: '分析请求失败，请检查网络连接',
      timestamp: new Date().toISOString()
    });
  } finally {
    analyzing.value = false;
  }
};

const clearInput = () => {
  inputText.value = '';
  chatHistory.value = [];
  medicalReport.value = '';
};

const generateReport = async () => {
  if (!chatHistory.value.length) return;
  
  generatingReport.value = true;
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/medical/generate-report`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_history: chatHistory.value,
        patient_info: {
          name: '患者',
          age: '未知',
          gender: '未知',
          history: '无'
        }
      })
    });
    
    if (response.ok) {
      const result = await response.json();
      medicalReport.value = result.report;
    } else {
      alert('报告生成失败');
    }
  } catch (error) {
    console.error('生成报告失败:', error);
    alert('报告生成失败');
  } finally {
    generatingReport.value = false;
  }
};

const downloadReport = () => {
  if (!medicalReport.value) return;
  
  const blob = new Blob([medicalReport.value], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `患者_诊疗报告_${new Date().toISOString().split('T')[0]}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

const renderMarkdown = (content: string) => {
  // 简单的markdown渲染，处理基本格式
  return content
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/### (.*)/g, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/- (.*)/g, '<li>$1</li>')
    .replace(/\n/g, '<br>')
    .replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
};

// 自动滚动到医疗对话底部
const scrollToMedicalChatBottom = () => {
  nextTick(() => {
    if (medicalChatContainer.value) {
      medicalChatContainer.value.scrollTop = medicalChatContainer.value.scrollHeight;
    }
  });
};

// 监听聊天历史变化，自动滚动到底部
watch(() => chatHistory.value.length, () => {
  scrollToMedicalChatBottom();
});
</script>

